/* eslint-disable brace-style */
import axios from 'axios'
import {
  Message
} from 'element-ui'
import {
  ParamArr
} from '../../public/js/paramarr'
import {
  getToken,
  removeToken
} from '@/utils/auth' // get token from cookie
import {
  resetRouter
} from '@/router'
import Global from '../../public/js/global'
const BASEURL = process.env.NODE_ENV === 'production' ? '/CallFunc.aom' : '/devApi'
import vue from '@/main'
// const BASEURL = '/devApi';
// 创建axios 实例对象
const service = axios.create({
  baseURL: BASEURL,
  timeout: 999999999, // 不设置超时
  method: 'post'
})

let requestOptions = {
  isShowErrorMsg: true // 是否提示错误信息（默认提示）
}

// 添加请求拦截器
service.interceptors.request.use(function(config) {
  var s = window.location.pathname
  // var n = (s.split('/')).length - 1;
  var vPar = config.vPar
  var options = config.options

  // 消息推送请求不影响上一个请求是否显示错误信息
  if (config.lpName !== 'GetWebJsonMessage') {
    requestOptions = {
      isShowErrorMsg: true
    }
  }

  if (options) {
    requestOptions = {
      ...requestOptions,
      ...options
    }
  }

  // 当请求方法不是消息推送时 默然加提示
  if (config.lpName !== 'GetWebJsonMessage') {
    vue.$showLoading('正在加载...')
      // 屏蔽右键自带菜单
      .$el.oncontextmenu = () => {
        event.returnValue = false
      }
  }
  // 取当前的Token
  var token = getToken('Token')
  vPar.setGlobalId(token + s)
  vPar.setDMName(config.dmName)
  vPar.setLPName(config.lpName)
  if (token !== '') {
    vPar.setStr('Token', token)
  }
  // 如果是上传文件传fd
  if (config.upload) {
    var fd = new FormData()
    fd.append('json', vPar.toJson())
    fd.append('file', config.fileObj)
    config.data = fd
  } else {
    config.data = vPar.toJson()
  }
  return config
}, function(error) {
  console.log(error)
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
service.interceptors.response.use(function(response) {
  vue.$closeLoading()
  // 对响应成功做点什么
  const res = response.data
  var vRst
  if (typeof res === 'string') {
    vRst = new ParamArr(Global.parseWebJson(res))
  } else {
    vRst = new ParamArr(res)
  }
  var message = vRst.getReturn() || ''
  if (message === '') // 服务器返回成功
  {
    return vRst
  } else {
    if (vRst.getBool('TokenError')) {
      Message.closeAll()
      Message({
        message: '登入失效请重新登入',
        type: 'error',
        duration: 5 * 1000
      })
      removeToken()
      resetRouter()
    } else {
      (response.config.isShowErrorMsg !== false) && Message({
        message: message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject({
      vPar: vRst,
      sError: message
    })
  }
}, function(error, vPar) {
  Message.closeAll()
  console.log(error)

  // 对响应错误做点什么
  Message({
    showClose: true,
    message: '服务器异常',
    type: 'error',
    duration: 5000
  })
  // removeToken() // must remove  token  first
  // resetRouter()
  return Promise.reject(error)
})

export default service
